<script lang="ts" setup>
import { onMounted, ref } from "vue";
import {
  CalendarOutlined,
  EyeOutlined,
  LikeOutlined,
} from "@ant-design/icons-vue";
import type { BlogVo, TreeNode } from "@/type";
import { postApi, tagApi } from "@/api";
import dayjs from "dayjs";
import { filterHtmlTags, truncateString } from "@/utils";
import { useRouter } from "vue-router";
const router = useRouter();
// 时间导航相关
const selectedYear = ref<number | null>(null);
const selectedMonth = ref<number | null>(null);
const totalArticles = ref(0);
const expandedKeys = ref<(string | number)[]>([
  // 获取当前年份
  new Date().getFullYear().toString(),
]);
const selectedKeys = ref<(string | number)[]>([]);
const autoExpandParent = ref<boolean>(true);
// 文章排序和筛选
const loading = ref(false);
const params = ref({
  page: 1,
  pageSize: 10,
  sortBy: "date",
  filterTag: "",
  date: String(expandedKeys.value),
});
const filterTag = ref("");
const onExpand = (keys: (string | number)[]) => {
  expandedKeys.value = keys;
  autoExpandParent.value = false;
};

const onSelect = (keys: (string | number)[]) => {
  if (keys.length > 0) {
    const key = keys[0].toString();
    if (key.length === 4) {
      selectedYear.value = Number(key);
      selectedMonth.value = null;
    } else if (key.length > 4) {
      selectedYear.value = Number(key.substring(0, 4));
      selectedMonth.value = Number(key.substring(4));
    }
  } else {
    selectedYear.value = null;
    selectedMonth.value = null;
  }
  selectedKeys.value = keys;
  params.value.date = keys[0] as string;
  getArchivePost();
  params.value.page = 1;
};

const treeData = ref<TreeNode[]>([]);

// 分页相关
const onPageChange = (page: number) => {
  params.value.page = page;
  window.scrollTo({ top: 0, behavior: "smooth" });
  getArchivePost();
};

// 标签颜色
const tagColors = [
  "blue",
  "cyan",
  "geekblue",
  "gold",
  "green",
  "lime",
  "magenta",
  "orange",
  "pink",
  "purple",
  "red",
  "volcano",
];

const tagColorMap = ref<Record<string, string>>({});

// 获取标签颜色
const getTagColor = (tag: string) => {
  if (!tagColorMap.value[tag]) {
    const randomIndex = Math.floor(Math.random() * tagColors.length);
    tagColorMap.value[tag] = tagColors[randomIndex];
  }
  return tagColorMap.value[tag];
};

// 文章数据
const articles = ref<BlogVo[]>([]);

// 计算所有标签
const allTags = ref<{ id: number; title: string }[]>([]);

// 获取归档数据
const getArchive = async () => {
  const res = await postApi.getArchive();
  treeData.value = res.date;
};
// 获取文章
const getArchivePost = async () => {
  loading.value = true;
  // 查询对应标签的id
  if (filterTag.value === "") {
    params.value.filterTag = "";
  } else {
    const id = allTags.value.find(
      (tagObj) => tagObj.title === filterTag.value,
    )?.id;
    console.log(filterTag.value);
    params.value.filterTag = String(id);
  }
  const param = {
    ...params.value,
  };
  const res = await postApi.getTimeline(param);
  totalArticles.value = res.count;
  articles.value = res.rows.map((item: BlogVo) => {
    return {
      ...item,
      // 处理日期8小时格式
      createdAt: dayjs(String(item.createdAt)).format("YYYY-MM-DD HH:mm:ss"),
      excerpt: truncateString(filterHtmlTags(item.excerpt), 50),
    };
  });
  loading.value = false;
};
const getTagList = async () => {
  const res = await tagApi.getTagList();
  allTags.value = res.list.map((item) => {
    return {
      title: item.name,
      id: item.id,
    };
  });
};
// 点击标签
const changeTag = (tag: string) => {
  // 查询对应标签的id
  filterTag.value = tag;
  getArchivePost();
  params.value.page = 1;
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: "smooth" });
};
onMounted(() => {
  // 初始化标签颜色
  allTags.value.forEach((tag: { id: number; title: string }) => {
    getTagColor(tag.title);
  });
  // 模拟加载
  getArchive();
  getTagList();
  getArchivePost();
});
const handleClick = (item: BlogVo) => {
  router.push({ name: "blogItem", params: { id: item.id, title: item.title } });
};
</script>

<template>
  <div class="min-h-screen archiving">
    <!-- 主要内容区域 -->
    <main class="container mx-auto px-4 py-8">
      <div class="flex flex-col lg:flex-row gap-8">
        <!-- 左侧时间导航 -->
        <div class="lg:w-1/5" style="margin-top: 3.2rem">
          <div
            class="bg-white rounded-lg shadow-md p-6 sticky top-20 flex flex-col"
          >
            <h2 class="text-xl font-bold mb-4 text-gray-800">时间导航</h2>
            <div class="flex-1 overflow-y-auto pr-2 custom-scrollbar">
              <a-tree
                :tree-data="treeData"
                :expandedKeys="expandedKeys"
                :selectedKeys="selectedKeys"
                @select="onSelect"
                :autoExpandParent="autoExpandParent"
                @expand="onExpand"
              >
                <template #title="{ title, key, count }">
                  <span
                    class="cursor-pointer hover:text-blue-500 transition-colors"
                    :class="{
                      'font-bold text-blue-600':
                        selectedYear === key || selectedMonth === key,
                    }"
                  >
                    {{ title }}
                    <span
                      v-if="key.toString().length === 4"
                      class="text-gray-500 text-sm ml-2"
                    >
                      ({{ count }}篇)
                    </span>
                  </span>
                </template>
              </a-tree>
            </div>
          </div>
        </div>
        <!-- 右侧文章列表 -->
        <div class="lg:w-3/4 sm:pt-12">
          <div class="rounded-lg shadow-md p-6 mb-6 list">
            <div class="flex items-center justify-between flex-wrap mb-6">
              <h2 class="text-2xl font-bold text-gray-800 fel">
                {{
                  selectedYear
                    ? `${selectedYear}年${
                        selectedMonth ? selectedMonth + "月" : ""
                      }文章`
                    : "全部文章"
                }}
              </h2>
              <div class="flex items-center space-x-4">
                <a-select
                  v-model:value="params.sortBy"
                  style="width: 140px"
                  class="!rounded-button"
                  @change="getArchivePost"
                >
                  <a-select-option value="date">按日期排序</a-select-option>
                  <a-select-option value="popular"
                    >按阅读量排序</a-select-option
                  >
                </a-select>
                <a-select
                  v-model:value="filterTag"
                  style="width: 140px"
                  placeholder="筛选标签"
                  class="!rounded-button"
                  @change="getArchivePost"
                >
                  <a-select-option value="">全部标签</a-select-option>
                  <a-select-option
                    v-for="tag in allTags"
                    :key="tag.id"
                    :value="tag.title"
                  >
                    {{ tag.title }}
                  </a-select-option>
                </a-select>
              </div>
            </div>

            <!-- 文章列表 -->
            <a-spin :spinning="loading">
              <div v-if="articles.length > 0">
                <div
                  v-for="(article, index) in articles"
                  :key="article.id"
                  class="mb-6"
                >
                  <div
                    class="flex flex-col md:flex-row gap-4 p-4 hover:bg-gray-50 rounded-lg transition-colors border border-gray-100"
                  >
                    <div
                      class="sm:w-1/4 h-48 md:h-40 overflow-hidden rounded-lg"
                    >
                      <img
                        :src="article.coverImage"
                        :alt="article.title"
                        class="w-full h-full object-cover object-top transition-transform hover:scale-105 duration-300"
                      />
                    </div>
                    <div class="sm:w-3/4 flex flex-col justify-between">
                      <div>
                        <h3
                          class="text-xl font-bold mb-2 text-gray-800 hover:text-blue-600 transition-colors cursor-pointer"
                          @click="handleClick(article)"
                        >
                          {{ article.title }}
                        </h3>
                        <p class="text-gray-600 mb-3 line-clamp-2">
                          {{ article.excerpt }}
                        </p>
                        <div class="flex flex-wrap gap-2 mb-3">
                          <a-tag
                            v-for="tag in article.tags"
                            :key="tag"
                            :color="getTagColor(tag)"
                            class="cursor-pointer"
                            @click="changeTag(tag)"
                          >
                            {{ tag }}
                          </a-tag>
                        </div>
                      </div>
                      <div class="flex text-sm text-gray-500 mt-2 flex-wrap">
                        <span class="flex items-center mr-6">
                          <calendar-outlined class="mr-1" />
                          {{ article.createdAt }}
                        </span>
                        <span class="flex items-center mr-6">
                          <LikeOutlined class="mr-1" />
                          {{ article.likes }} 喜欢
                        </span>
                        <span class="flex items-center">
                          <eye-outlined class="mr-1" />
                          {{ article.views }} 阅读
                        </span>
                      </div>
                    </div>
                  </div>
                  <a-divider v-if="index < articles.length - 1" class="my-6" />
                </div>
              </div>
              <a-empty v-else description="暂无符合条件的文章" />
            </a-spin>

            <!-- 分页 -->
            <div class="mt-8 flex justify-center">
              <a-pagination
                v-model:current="params.page"
                :total="totalArticles"
                :pageSize="params.pageSize"
                show-quick-jumper
                @change="onPageChange"
              />
            </div>
          </div>
        </div>
      </div>
    </main>
    <!-- 回到顶部 -->
    <a-back-top />
  </div>
</template>

<style scoped>
.list {
  background: rgb(255, 255, 255, 0.8);
  border-radius: 5px;
}
</style>
